/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.wrapper.commons;


import org.pajamas.protocol.Wrapper;

import java.util.Optional;
import java.util.function.Supplier;

import javax.annotation.Nullable;

/**
 * @author william
 * @since 2023/12/31
 */

public abstract class AbstractWrapper<T> implements Wrapper<T> {
    private T value;

    protected AbstractWrapper(T value) {
        this.value = value;
    }

    @Override
    public void wrap(@Nullable T value) {
        this.value = value;
    }

    @Nullable
    @Override
    public T unwrap() {
        return this.value;
    }

    public T unwrapIfAbsent(T other) {
        T property = this.unwrap();
        return this.isPresent() ? property : other;
    }

    public T unwrapIfAbsent(Supplier<T> supplier) {
        return unwrapIfAbsent(supplier.get());
    }

    @SuppressWarnings("unchecked")
    public Class<T> getValueClass() {
        return this.isPresent() ? (Class<T>) this.unwrap().getClass() : null;
    }

    public boolean isSuperClassOf(Class<?> aClass) {
        if (!this.isPresent()) {
            throw new IllegalStateException("please check out wrapper.value exists ahead");
        }
        if (aClass == null) {
            throw new IllegalArgumentException("please check out aClass exists ahead");
        }
        return this.getValueClass().isAssignableFrom(aClass);
    }

    public boolean isChildClassOf(Class<?> aClass) {
        return !isSuperClassOf(aClass);
    }

    public Optional<T> asOptional() {
        return Optional.ofNullable(this.unwrap());
    }
}
